#include "../include/Backup.h"

bool Backup::backupByMemory(string && content, string objectName) {
    /* 初始化网络等资源。*/
    // InitializeSdk();

    // 1. 初始化OSS账号信息
    std::string endpoint = "oss-cn-wuhan-lr.aliyuncs.com";
    std::string accessKeyId = "LTAI5tRxD35QahXZe7a2Dgen";
    std::string accessKeySercret = "li1qXOj3ZAOMWJZOUxG7FjxKmt8MP8";
    std::string region = "cn-wuhan";

    ClientConfiguration conf;
    OssClient client {endpoint ,accessKeyId, accessKeySercret, conf};
    client.SetRegion(region);

    // 2. 上传文件
    std::string bucketName = "xjhcloud";

    objectName = objectName.substr(2);
    // cout << "[objectName]: " << objectName << endl;
    // cout << "[content]: " << content << endl;

    std::shared_ptr<std::iostream> stream = std::make_shared<std::stringstream>(std::move(content));

    PutObjectRequest request { bucketName, objectName, stream };    // 创建请求

    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /* 异常处理。*/
        std::cout << "PutObject fail" <<
        ", code:" << outcome.error().Code() <<
        ", message:" << outcome.error().Message() <<
        ", requestId:" << outcome.error().RequestId() << std::endl;
        return false;
    }

    /* 释放网络等资源。*/
    // ShutdownSdk();

    return true;
}

bool Backup::backupByFile(string srcpath, string objectName) {
    // 1. 初始化OSS账号信息
    std::string endpoint = "oss-cn-wuhan-lr.aliyuncs.com";
    std::string accessKeyId = "LTAI5tRxD35QahXZe7a2Dgen";
    std::string accessKeySercret = "li1qXOj3ZAOMWJZOUxG7FjxKmt8MP8";
    std::string region = "cn-wuhan";

    ClientConfiguration conf;
    OssClient client { endpoint, accessKeyId, accessKeySercret, conf };
    client.SetRegion(region);

    // 2. 上传文件
    std::string bucketName = "xjhcloud";
    objectName = objectName.substr(2);
    srcpath = srcpath.substr(2);
    // std::string objectName = "dir/a.txt";
    // auto outcome = client.PutObject(bucketName, objectName, "a.txt");   // a.txt 是本地文件的路径
    auto outcome = client.PutObject(bucketName, objectName, srcpath);

    if (!outcome.isSuccess()) {
        /* 异常处理。*/
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return false;
    }

    return true;
}

 void Backup::start() {
    InitializeSdk();
}
 void Backup::stop() {
    ShutdownSdk();
}